//
//  UPaySDK.m
//  UPaySDK
//
//  Created by xu yao on 2021/3/4.
//

#import "UPaySDK.h"
#import "UWebViewController.h"
#import "EnvironmentDefine.h"
#import "UAlipay.h"
#import "UWeChat.h"
#import "UBaseResp.h"
#import "UGZRCpay.h"
@interface UPaySDK ()

@property (nonatomic, strong) NSArray *activePlatforms;
@property (nonatomic, copy) USDKImportHandler importHandler;
@property (nonatomic, copy) USDKConfigurationHandler configurationHandler;
@property (nonatomic, copy) USDKPayResultHandler payResultHandle;
@property (nonatomic, strong) UWebViewController *webViewController;
@end

static UPaySDK *currentHelper = nil;
@implementation UPaySDK

#pragma mark - 初始化
+ (void)registerActivePlatforms:(NSArray *)activePlatforms
                       onImport:(USDKImportHandler)importHandler
                onConfiguration:(USDKConfigurationHandler)configurationHandler {
    UPaySDK *sdk = [UPaySDK currentHelper];
    sdk.importHandler = importHandler;
    sdk.configurationHandler = configurationHandler;
    sdk.activePlatforms = activePlatforms;
}

#pragma 进入支付页面
+ (void)payInfoPageWithCashStageSessionId:(NSString *)stageSessionURL onPayResult:(nonnull USDKPayResultHandler)payResultHandle{
    if (!stageSessionURL.length) {
        LCLog(@"stageSessionURL不能为空");
        return;
    }
    currentHelper.payResultHandle = payResultHandle;
    UINavigationController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    if (rootVC) {
        [rootVC dismissViewControllerAnimated:YES completion:nil];
        UWebViewController *webViewController = [[UWebViewController alloc] init];
        webViewController.stageSessionURL = stageSessionURL;
//        webViewController.modalPresentationStyle = UIModalPresentationFullScreen;
//        [rootVC presentViewController:nvc animated:YES completion:nil];
        [rootVC pushViewController:webViewController animated:YES];
        currentHelper.webViewController = webViewController;
    }
}

+ (void)closecheckstand {
    if (currentHelper.webViewController) {
//        [currentHelper.webViewController dismissViewControllerAnimated:YES completion:nil];
        [currentHelper.webViewController.navigationController popViewControllerAnimated:YES];
    }
}

#pragma 支付
+ (void)payActivePlatform:(USDKPlatformType)activePlatform
                payFrameData:(id)payFrameData {
    switch (activePlatform) {
        case USDKPlatformTypeWeChat:
        {
            [self wechatPay:payFrameData];
        }
            break;
        case USDKPlatformTypeAliPay:
        {
            [self alipay:payFrameData];
        }
        default:
            break;
    }
}

#pragma 微信支付
+ (void)wechatPay:(UPayReq *)payReq {
    [UWeChat weChatPayWithPayReq:payReq];
}

#pragma 支付宝支付
+ (void)alipay:(NSString *)payURL {
    [UAlipay alipayOrder:payURL];
}

#pragma mark 黔农云支付
+ (void)GZRCpay:(UGZRCpayModel *)orderInfo {
    [[UGZRCpay currentHelper] gzrcpayModel:orderInfo callback:currentHelper.payResultHandle];
}

+ (UPaySDK *)currentHelper {
    if (currentHelper == nil)
        currentHelper = [[UPaySDK alloc] init];
    
    return currentHelper;
}


- (instancetype)init {
    if (self = [super init]) {
        
    }
    return self;
}

- (void)setActivePlatforms:(NSArray *)activePlatforms {
    // 去掉重复的
    NSSet *set = [NSSet setWithArray:activePlatforms];
    _activePlatforms = [set allObjects];
    
    for (int index = 0; index < activePlatforms.count; index ++) {
        USDKPlatformType platfromType = [activePlatforms[index] integerValue];
        //让使用的地方配置对应平台的链接
        if (self.importHandler) {
            self.importHandler(platfromType);
        }
        if (self.configurationHandler) {
            self.configurationHandler(platfromType, @{}.mutableCopy);
        }
    }
}

+ (void)handleOpenURL:(id)URLContexts {
    if ([URLContexts isKindOfClass:[NSURL class]]) {
        NSURL *url = URLContexts;
        if ([url.scheme hasPrefix:@"wx"] && [url.host isEqualToString:@"pay"]) {
            [UWeChat handleOpenURL:url onPayResult:currentHelper.payResultHandle];
            return;
        }
        if ([url.scheme hasPrefix:@"safepay"]) {
            [UAlipay handleOpenURL:url onPayResult:currentHelper.payResultHandle];
            return;
        }
        if ([url.scheme hasPrefix:@"com.onebuygz.ag.xnjh"]) {
            //黔农云支付结果回调，请以查询结果为准
            [UGZRCpay handleOpenURL:url onPayResult:currentHelper.payResultHandle];
        }
    } else if ([URLContexts isKindOfClass:[NSSet class]]){
        NSString *version= [UIDevice currentDevice].systemVersion;
        if (version.doubleValue >= 13.0) {
            for (UIOpenURLContext *contexts in URLContexts) {
                if ([contexts isKindOfClass:[UIOpenURLContext class]]) {
                    if ([contexts.URL.scheme hasPrefix:@"wx"] && [contexts.URL.host isEqualToString:@"pay"]) {
                        [UWeChat handleOpenURL:contexts.URL onPayResult:currentHelper.payResultHandle];
                        break;
                    }
                    if ([contexts.URL.scheme hasPrefix:@"safepay"]) {
                        [UAlipay handleOpenURL:contexts.URL onPayResult:currentHelper.payResultHandle];
                        break;
                    }
                    if ([contexts.URL.scheme hasPrefix:@"com.onebuygz.ag.xnjh"]) {
                        //黔农云支付结果回调，请以查询结果为准
                        [UGZRCpay handleOpenURL:contexts.URL onPayResult:currentHelper.payResultHandle];
                        break;
                    }
                }
                
            }
        } else {
            LCLog(@"请实现application:openURL:options:方法");
        }
    }
}

- (void)onResp:(UBaseResp*) resp {
    NSString *message = resp.errStr;
    if (resp.errCode == UWXSuccess) {
        message = @"支付成功";
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TopupPaySuccess" object:nil userInfo:nil];
    } else {
        message = @"支付失败";
    }
    UIAlertController *alertCtl = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertCtl addAction: [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (resp.errCode == UWXSuccess) {

        }
    }]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertCtl animated:YES completion:nil];
}
@end
